package com.product.shopping.service.impl;

import com.product.shopping.Rabbit.ErrorCodeEnum;
import com.product.shopping.Rabbit.MsgProducer;
import com.product.shopping.Rabbit.ServerBizException;
import com.product.shopping.config.RedisService;
import com.product.shopping.entity.Product;
import com.product.shopping.dao.ProductDao;
import com.product.shopping.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Product)表服务实现类
 *
 * @author makejava
 * @since 2020-03-10 23:34:05
 */
@Service("productService")
public class ProductServiceImpl implements ProductService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ProductDao productDao;
    @Autowired
    RedisService redisService;
    @Autowired
    MsgProducer msgProducer;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Product queryById(Integer id) {
        return this.productDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<Product> queryAllByLimit(int offset, int limit) {
        return this.productDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param product 实例对象
     * @return 实例对象
     */
    @Override
    public Product insert(Product product) {
        this.productDao.insert(product);
        return product;
    }

    /**
     * 修改数据
     *
     * @param product 实例对象
     * @return 实例对象
     */
    @Override
    public Product update(Product product) {
        this.productDao.update(product);
        return this.queryById(product.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.productDao.deleteById(id) > 0;
    }

    /**
     * 商品秒杀
     * @param Pid
     * @param Uid
     * @return
     * @throws ServerBizException
     */
    int i = 0;
    public boolean secondsKill(String Pid, String Uid) throws ServerBizException {
        boolean result = true;
        //根据商品id获取Redis中的库存数量
        String num = redisService.get(Pid).toString();
        logger.info("redis>>>>>>>>>>"+num);
        if(new Integer(num) <= 0) {
            result = false;
            throw new ServerBizException(ErrorCodeEnum.PRODUCT_INVENTORY_IS_NULL);
        }
        //消息入队，调用相关方法
        msgProducer.sendMsg(Pid);
        //只为验证请求及发送消息次数
        logger.info("send msg >>>>>>>>>>"+i++);
        return result;
    }
}
